package vn.ducquoc.cassandra;

import java.nio.ByteBuffer;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Cassandra Insert example.
 * 
 * @author ducquoc
 */
public class CassandraThriftInsert {
  public static final String CASSANDRA_HOST = "192.168.22.84";// "tlcirrusa03";
  public static final int CASSANDRA_PORT = 9160;

  public static final String SAMPLE_KEYSPACE = "Keyspace1";
  public static final String SAMPLE_COLUMN_FAMILY = "Standard1";

  public static final ByteBuffer COLUMN = ByteBufferUtil.bytes("enabled");
  public static final ByteBuffer VALUE2 = ByteBufferUtil.bytes("false");

  static final long TIMESTAMP = 1010102011000L;// System.currentTimeMillis();

  public static void main(String[] args) throws Exception {

    TTransport transport = new TFramedTransport(new TSocket(CASSANDRA_HOST,
            CASSANDRA_PORT));
    TProtocol protocol = new TBinaryProtocol(transport);
    Cassandra.Client client = new Cassandra.Client(protocol);
    transport.open();

    client.set_keyspace(SAMPLE_KEYSPACE);

    // define column parent
    ColumnParent parent = new ColumnParent(SAMPLE_COLUMN_FAMILY);

    // define row id
    ByteBuffer rowkeyId = ByteBufferUtil.bytes("CommitLog");

    // define column to add
    Column colFirstLevel = new Column();
    colFirstLevel.setName(COLUMN);
    colFirstLevel.setValue(VALUE2);
    colFirstLevel.setTimestamp(TIMESTAMP);

    // define consistency level
    ConsistencyLevel consistencyLevel = ConsistencyLevel.ONE;

    // execute insert
    client.insert(rowkeyId, parent, colFirstLevel, consistencyLevel);
    System.out.println("Insertion/Update Thrift " + client.describe_version());

    // release resources
    transport.flush();
    transport.close();
  }

}